package com.mvc.rpc.feign;

import com.mvc.common.excetion.FeignResponseException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;

/**
 * 错误解析
 * @author JayEinstein
 */
@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        int status = response.status();
        log.info("feign status: {}", status);

        try {
            InputStream inputStream = response.body().asInputStream();
            byte[] bytes = Util.toByteArray(inputStream);
            String str = new String(bytes);
            return new FeignResponseException(status, str);
        } catch (IOException e) {
            // ignore
        }

        return new FeignResponseException(status);
    }

    private static boolean isClientError(int status) {
        return status >= 400 && status < 500;
    }

    private static boolean isServerError(int status) {
        return status >= 500 && status <= 599;
    }

}
